//
//  RxBluetoothVC.swift
//  RXSwiftDemo1
//
//  Created by mac on 2025/3/4.
//

import UIKit
import RxSwift
import RxCocoa
import Loaf
import CoreBluetooth

class RxBluetoothVC: UIViewController {
    
    @IBOutlet weak var blueTab: UITableView!
    @IBOutlet weak var blueButton: UIButton!
    
    @IBOutlet weak var jumpMsgButton: UIButton!
    private let disposeBag = DisposeBag()
    private let bluetoothManager = XCBluetoothManager.instance
    
    private let devices = BehaviorRelay<[XCBlueToothModel]>(value: [])
    
    let activityIndicator = UIActivityIndicatorView(style: .large)
    
    let jumpPublishSubject: BehaviorSubject<Bool> = BehaviorSubject(value: true)
    
    private var msgVc: RXMessageVC?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        activityIndicator.center = view.center
        activityIndicator.hidesWhenStopped = true
        view.addSubview(activityIndicator)
        
        blueTab.register(UINib(nibName: "DeviceCell", bundle: nibBundle), forCellReuseIdentifier: "DeviceCell")
        
        bluetoothManager.bluetoothStateObservable
            .subscribe(onNext: {[weak self] blueState in
                self?.updateButtonTitle(for: blueState)
            })
            .disposed(by: disposeBag)
        
        blueButton.rx.tap
            .withLatestFrom(bluetoothManager.bluetoothStateObservable)
            .subscribe(onNext: {[weak self] blueState in
                self?.handleButtonAction(for: blueState)
            })
            .disposed(by: disposeBag)
        
        devices.bind(to: blueTab.rx.items(cellIdentifier: "DeviceCell", cellType: DeviceCell.self)) {[weak self] row, model, cell in
            
            guard let self = self else { return }
            print("deviceName: \(String(describing: model.deviceName)) rssi:\(String(describing: model.rssi))")
            cell.deviceName?.text = model.deviceName ?? "未知设备"
            cell.deviceRssi?.text = "\(model.rssi!)"
            cell.conneected?.text = model.isConnected ? "可连接":"已连接"
            cell.macaddress?.text = model.macAddress
            
            if model.peripheral == self.bluetoothManager.connectedPeripheral {
                cell.backgroundColor = .red
            }else {
                cell.backgroundColor = .white
            }
        }
        .disposed(by: disposeBag)
        
        blueTab.rx.modelSelected(XCBlueToothModel.self)
            .subscribe(onNext: { [weak self] selectModel in
                print("selectmodel:\(selectModel)")
                
                guard let self = self else { return }
                
                if self.blueTab.indexPathForSelectedRow != nil {
                    
                    if self.bluetoothManager.connectedPeripheral == selectModel.peripheral {
                        self.didDisconnected()
                    }else {
                        if bluetoothManager.connectedPeripheral != nil {
                            self.didDisconnected()
                        }
                        self.connectDevice(selectModel: selectModel)
                    }
                }
            })
            .disposed(by: disposeBag)
        
        jumpPublishSubject.bind(to: jumpMsgButton.rx.isHidden)
            .disposed(by: disposeBag)
        
        jumpMsgButton.rx.tap
            .subscribe(onNext: {
                let vc = RXMessageVC()
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: false)
            })
            .disposed(by: disposeBag)
        
    }
    
    deinit {
        print("✅ RxBluetoothVC 已释放")
    }
    
}

extension RxBluetoothVC {
    
    private func connectDevice(selectModel: XCBlueToothModel){
        self.bluetoothManager.connect(to: selectModel.peripheral!)
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { connectState in
                self.blueTab.reloadData()
                self.jumpPublishSubject.onNext(connectState != .connected)
                switch connectState {
                case .connecting:
                    self.activityIndicator.startAnimating()
                case .connected:
                    Loaf("蓝牙连接成功", state: .success, sender: self).show()
                    self.activityIndicator.stopAnimating()
                case .disconnected:
                    Loaf("蓝牙断开连接", state: .warning, sender: self).show()
                    self.activityIndicator.stopAnimating()
                    
                case .failed(let error):
                    Loaf("蓝牙连接错误 -> \(error.localizedDescription)", state: .error, sender: self).show()
                    self.activityIndicator.stopAnimating()
                    
                    if let error = error as NSError? {
                        switch error.code {
                        case CBError.connectionTimeout.rawValue:
                            print("设备远离了导致的断开")
                            
                        case CBError.peripheralDisconnected.rawValue:
                            print("设备主动断开导致的断开")
                        default:
                            print("断开失败 error == \(error)")
                            return
                        }
                    }
                }
            })
            .disposed(by: self.disposeBag)
    }
    
    private func didDisconnected() {
        self.bluetoothManager.disconnect()
            .subscribe(onNext: { disconnectState in
                self.blueTab.reloadData()
                switch disconnectState {
                case .disconnecting:
                    self.activityIndicator.startAnimating()
                case .disconnected:
                    Loaf("蓝牙断开连接", state: .success, sender: self).show()
                    self.activityIndicator.stopAnimating()
                    
                case .connected: break
                case .connecting: break
                @unknown default: break
                }
            },onError: {error in
                Loaf("蓝牙连接错误 -> \(error.localizedDescription)", state: .error, sender: self).show()
                self.activityIndicator.stopAnimating()
            })
            .disposed(by: disposeBag)
    }
    
    private func updateButtonTitle(for state: BluetoothState) {
        switch state {
        case .poweredOn:
            blueButton.setTitle("获取蓝牙设备", for: .normal)
        case .poweredOff, .unauthorized, .unsupported, .unknown, .resetting:
            blueButton.setTitle("请打开蓝牙权限", for: .normal)
        }
    }
    
    private func handleButtonAction(for state: BluetoothState) {
        switch state {
        case .poweredOn:
            bluetoothManager.scanForPeripherals()
                .subscribe(onNext: { [weak self] devices in
                    self?.devices.accept(devices)
                    self?.blueButton.isHidden = true
                }, onError: { error in
                    print("扫描设备失败: \(error.localizedDescription)")
                })
                .disposed(by: disposeBag)
        case .poweredOff, .unauthorized, .unsupported, .unknown, .resetting:
            // 跳转到设置页面
            if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    
}


